let brodacastChannel = null
if(window.BroadcastChannel){
    brodacastChannel = new BroadcastChannel('login')
}

// 等待回调
const wait = () => {
  return new Promise((resolve, reject) => {
    if(brodacastChannel){
      brodacastChannel.onmessage = (e) => {
        resolve(e.data)
      }
    } else {
      const data = localStorage.getItem('login')
      resolve(JSON.parse(data))
    }
  })
}

// 发送消息
const send = (data) => {
  if(brodacastChannel){
    brodacastChannel.postMessage(data)
  } else {
    localStorage.setItem('login', JSON.stringify(data))
  }
}

// 销毁
const clear = () => {
  if(brodacastChannel){
    brodacastChannel.close()
    brodacastChannel = null
  } else {
    localStorage.removeItem('login')
  }
}

export default {
  wait,
  send,
  clear
}